<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * User class
 *
 * @category	Admin
 */
class UserAction extends AdminAction
{

	protected $User;
	
	
	//初始化
	public function _initialize()
	{
		parent::_initialize();
		$this->User = D('User');
	}


	//搜索用户
	public function searchUser()
	{
		
		$UserGroup  = D('UserGroup');
		$userGroups = $UserGroup->where($where)->select();
		
		$this->assign('userGroups', $userGroups);
		$this->display();
	}


	//用户列表
	public function userList()
	{
		
		import('ORG.Util.Page');
		
		$map = array();
		$parameter = '';
		
		/*----------------- 构建查询条件 ---------------*/
		if (!empty($_GET['user_group']) && 'all' != $_GET['user_group'])
		{
			$map['user_group'] = $_GET['user_group'];
			$parameter .= 'user_group='.$_GET['user_group'].'&';
		}
		if (!empty($_GET['username']))
		{
			$map['username'] = array('like','%'.$_GET['username'].'%');
			$parameter .= 'username='.$_GET['username'].'&';
		}
		if (!empty($_GET['email']))
		{
			$map['email'] = array('like','%'.$_GET['email'].'%');
			$parameter .= 'email='.$_GET['email'].'&';
		}
		if (!empty($_GET['point_count']))
		{
			$map['point_count'] = array($_GET['point_count_select'], intval($_GET['point_count']));
			$parameter .= 'point_count_select='.$_GET['point_count_select'].'&';
			$parameter .= 'point_count='.$_GET['point_count'].'&';
		}
		if (!empty($_GET['question_count']))
		{
			$map['question_count'] = array($_GET['question_count_select'], intval($_GET['question_count']));
			$parameter .= 'question_count_select='.$_GET['question_count_select'].'&';
			$parameter .= 'question_count='.$_GET['quesiton_count'].'&';
		}
		if (!empty($_GET['answer_count']))
		{
			$map['answer_count'] = array($_GET['answer_count_select'], intval($_GET['answer_count']));
			$parameter .= 'answer_count_select='.$_GET['answer_count_select'].'&';
			$parameter .= 'answer_count='.$_GET['answer_count'].'&';
		}
		if (!empty($_GET['register_date']))
		{
			$map['register_date'] = array($_GET['register_date_select'], $_GET['register_date']);
			$parameter .= 'register_date_select='.$_GET['register_date_select'].'&';
			$parameter .= 'user_register_date='.$_GET['user_register_date'].'&';
		}
		if (!empty($_GET['last_activity']))
		{
			$map['last_activity'] = array($_GET['last_activity_select'], strtotime($_GET['last_activity']));
			$parameter .= 'last_activity_select='.$_GET['last_activity_select'].'&';
			$parameter .= 'last_activity='.$_GET['last_activity'].'&';
		}

		$count = $this->User->where($map)->count();
		$Page  = new Page($count);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
		$userList   = $this->User->where($map)->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->assign('pagination', $pagination);
		$this->assign('userList', $userList);
		$this->display();
	}


	//新增用户
	public function addUser()
	{
		
		if ($this->isPost())
		{
		    $usernameValidated = is_valid_username($_POST['username']);
    		$passwordValidated = is_valid_password($_POST['password']);
    		$emailValidated    = is_valid_email($_POST['email']);
    		
    		if (true !== $usernameValidated)
    		{
    			$this->error(L($usernameValidated));
    		}
    		
    		if (true !== $emailValidated)
    		{
    			$this->error(L($emailValidated));
    		}
    		
    		if (true !== $passwordValidated)
    		{
    			$this->error(L($passwordValidated));
    		}

			//添加管理员检查
			$isFounder = is_founder($this->_admin['user_id']);
			if (!$isFounder && (1 == $_POST['admin_group']))
			{
				$this->error(L('no_perms_action'));
			}
            $salt = kg_password_salt();
            $password = kg_password_encrypt($_POST['password'], $salt);
            $points = get_activity_points('register');
			$data = array(
				'username'    => $_POST['username'],
				'email'       => $_POST['email'],
				'password'    => $password,
				'salt'        => $salt,
				'admin_group' => $_POST['admin_group'],
				'user_group'  => $_POST['admin_group'],
				'user_point'  => $points,
			);
			$lastID = $this->User->add($data);
			$jumpUrl = __URL__.'/editUser/user_id/'.$lastID;
			
			$this->assign('jumpUrl', $jumpUrl);
			$this->success(L('user_added_succeed'));
		}
		else
		{
			$UserGroup = D('UserGroup');
			$map = array('group_id' => array('in', array(1,2,3)));
			$adminGroups = $UserGroup->where($map)->select();
			
			$this->assign('adminGroups', $adminGroups);
			$this->display();
		}
	}


	//编辑用户
	public function editUser()
	{
		
		$userID = isset($_REQUEST['user_id']) ? intval($_REQUEST['user_id']) : 0;
		$user = $this->User->find($userID);
		
		$jumpUrl = __ACTION__.'/user_id/'.$userID;
		$this->assign('jumpUrl', $jumpUrl);

        if (empty($user))
        {
			$this->assign('jumpUrl', __URL__.'/userList');
		 	$this->error(L('user_does_not_exist'));
		}

        //编辑管理员检查
        $isFounder = is_founder($this->_admin['user_id']);
		if (!$isFounder && (1 == $user['admin_group']))
		{
			$this->error(L('no_perms_action'));
		}

		if ($this->isPost())
		{
			$data = array(
			    'admin_group'          => $_POST['admin_group'],
			    'gender'               => $_POST['gender'],
				'birthday'             => $_POST['birthday'],
				'website'              => $_POST['website'],
				'location'             => $_POST['location'],
				'about'                => $_POST['about'],
				'language'             => $_POST['language'],
				'timezone'             => $_POST['timezone'],
				'theme'                => $_POST['theme'],
				'new_answer_alert'     => $_POST['new_answer_alert'],
				'new_comment_alert'    => $_POST['new_comment_alert'],
				'new_follower_alert'   => $_POST['new_follower_alert'],
				'best_answer_alert'    => $_POST['best_answer_alert'],
				'allow_followed'       => $_POST['allow_followed'],
				'allow_contact'        => $_POST['allow_contact'],
				'allow_newsletter'     => $_POST['allow_newsletter'],
			);
			
            if (in_array($_POST['admin_group'], array(1,2,3)))
            {
                $data['user_group'] = $_POST['admin_group'];
            }
            else 
            {
            	//清除版主记录
            	$Moderator = D('Moderator');
            	$Moderator->deleteModerator($user['user_id']);
            	$data['user_group'] = 7;
            	
            }
            
			if (!empty($_POST['email']) && $_POST['email'] == $_POST['email_confirm'])
			{
			    $emailValidated = is_valid_email($_POST['email']);
				if (true !== $emailValidated)
	    		{
	    			$this->error(L($emailValidated));
	    		}
    			$data['email'] = $_POST['email'];
			}
			
			if (!empty($_POST['new_password']) && $_POST['new_password'] == $_POST['password_confirm'])
			{
				$passwordValidated = is_valid_password($_POST['new_password']);
				if (true !== $passwordValidated)
	    		{
	    			$this->error(L($passwordValidated));
	    		}
				$salt = kg_password_salt();
				$data['salt'] = $salt;
				$data['password'] = kg_password_encrypt($_POST['new_password'], $salt);
			}

			$this->User->where('user_id='.$userID)->save($data);
			
			$this->success(L('user_updated_succeed'));
		}
		else
		{
			$UserGroup  = D('UserGroup');
			$where = array('group_id' => array('in',array(1,2,3)));
			$adminGroups = $UserGroup->where($where)->select();
			$this->assign('adminGroups', $adminGroups);

			$boolRadios = array(1 => L('yes'), 0 => L('no'));
            $genderRadios = array(1=> L('gender_male'), 0 => L('gender_female'));

            $this->assign('genderRadios', $genderRadios);
			$this->assign('genderChecked', $user['gender']);

			$this->assign('languageOptions', get_site_languages());
			$this->assign('languageSelected',  $user['language']);

			$this->assign('themeOptions', get_site_themes());
			$this->assign('themeSelected',  $user['theme']);

			$this->assign('timezoneOptions', L('timezone_options'));
			$this->assign('timezoneSelected', $user['timezone']);

			$this->assign('newAnswerAlertRadios', $boolRadios);
			$this->assign('newAnswerAlertChecked', $user['new_answer_alert']);

			$this->assign('newCommentAlertRadios', $boolRadios);
			$this->assign('newCommentAlertChecked', $user['new_comment_alert']);

			$this->assign('newFollowerAlertRadios', $boolRadios);
			$this->assign('newFollowerAlertChecked', $user['new_follower_alert']);

			$this->assign('bestAnswerAlertRadios', $boolRadios);
			$this->assign('bestAnswerAlertChecked', $user['best_answer_alert']);

			$this->assign('allowFollowRadios', $boolRadios);
			$this->assign('allowFollowChecked', $user['allow_follow']);

			$this->assign('allowContactRadios', $boolRadios);
			$this->assign('allowContactChecked', $user['allow_contact']);

			$this->assign('allowNewsletterRadios', $boolRadios);
			$this->assign('allowNewsletterChecked', $user['allow_newsletter']);

			$this->assign('rs', $user);
			$this->display();
		}
	}


	//删除用户
	public function deleteUser()
	{
		if (empty($_POST['mods']))
		{
			$this->redirect('Admin-User/userList');
		}
		if (isset($_POST['action']['confirm']))
		{
		     $this->User->deleteUserByID($_POST['mods']);
    		$this->success(L('user_deleted_succeed'));
		}
		elseif (isset($_POST['action']['cancel']))
		{
			$this->redirect('Admin-User/userList');
		}
		else
		{
		    $this->assign('mods', $_POST['mods']);
		    $this->assign('action', __ACTION__);
            $this->confirm(L('del_user_confirm'));
		}
	}


	//审核用户
	public function approveUser()
	{

		if ($this->isPost())
		{
			if (empty($_POST['mods']))
			{
				$this->error(L('no_user_selected'));
			}
			else
			{
				$map = $where = array('user_id' => array('in', $_POST['mods']));
			    if (isset($_POST['action']['approve']))
			    {
			    	$UserFollow = D('UserFollow');
				    $users =  $this->User->where($map)->select();

				    //奖励邀请人以及增加关注
	    			foreach ($users as $user)
	    			{
	    			    if (!empty($user['inviter']))
	    			    {
	    			    	 $this->User->rewardInviter($user['inviter']);
	    			        $UserFollow->addFollow($user['user_id'], $user['inviter']);
	    			    }
	    			}
			    	 $this->User->where($where)->setField('user_group', 7);
			    	$message = L('user_approved_succeed');
			    }
			    elseif (isset($_POST['action']['disapprove']))
			    {
			    	 $this->User->where($where)->setField('user_group', 8); //加入禁止访问用户组
			    	$message = L('user_deleted_succeed');
			    }
			    $this->success($message);
			}
		}
		else
		{
			import('ORG.Util.Page');
			$where = array('user_group' => 4); //待验证用户组

			$count =  $this->User->where($where)->count();
			$Page  = new Page($count);
			$pagination = $Page->show();
			$userList =  $this->User->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();

			$this->assign('pagination', $pagination);
			$this->assign('userList', $userList);
			$this->display();
		}
	}

}
// End  Class

/* End of file UserAction.class.php */
/* Location: ./App/Lib/Action/Admin/UserAction.class.php */